package Main;

import homework_3_by_ly.Figure_Extract;
import homework_3_by_ly.ShazamHash;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;

import static FileReader.SourceReader.MusicFormatInspectionAndDataCollection;
import static homework_3_by_ly.FFT.fft;

/**
 * Created by ChenCheng on 16/11/7.
 * This class can get data from figure_extract part.
 */
public class ProjectManager
{

    public ArrayList<ShazamHash> getHashes(String url) throws IOException
    {
        Figure_Extract FE = new Figure_Extract(1);//参数为id
        double[][] splits = split(readMusic(url));
        int i=0;
        for(int j = 0; j < splits.length; j++)
        {
            FE.append(fft(splits[i]));
            i++;
        }
        ArrayList<ShazamHash> hashes = FE.combineHash();
        System.out.println("哈希个数：" + hashes.size());
        return hashes;
    }

    public String getName(String name)
    {
        System.out.println("歌曲名：" + name);
        return name;
    }

    private static double[][] split(double[] musicd)
    {

        int count = (int)(musicd.length/4096.0+1);
        double[][] al = new double[count][4096];

        int n = 0;
        for(int j=0;j<count - 1;j++)
        {
            for(int i=0;i<4096;i++)
            {
                al[j][i] = musicd[i + n * 4096];
            }
            n++;
        }
        return al;
    }

    private static double[] readMusic(String url) throws IOException
    {
        System.out.println(url);
        File file = new File(url);
        long fileSize = file.length();

        FileInputStream fi = new FileInputStream(file);
        byte[] buffer = new byte[(int) fileSize];
        int offset = 0;
        int numRead = 0;
        while (offset < buffer.length && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0)
        {
            offset += numRead;
        }

        // Make sure that all the data in the music is read
        if (offset != buffer.length)
        {
            throw new IOException("Could not completely read file " + file.getName());
        }

        // Inspect the format of the music and output the double array
        double[] musicData = MusicFormatInspectionAndDataCollection(buffer);
        return musicData;
    }
}
